import { Controller, Get } from '@nestjs/common';
import { ExcelService } from './excel.service';
import { Workbook, Worksheet, Cell, CellValue } from 'exceljs';
import { join } from 'path';

@Controller('excel')
export class ExcelController {
  constructor(private readonly excelService: ExcelService) {}

  @Get('parse')
  async parseExcel(): Promise<{ link: string; name: CellValue }[]> {
    const workbook = new Workbook();
    await workbook.xlsx.readFile(
      join(__dirname, '../../public/nest-docs.xlsx'),
    );
    const res: { link: string; name: CellValue }[] = [];
   

    workbook.eachSheet((sheet, i) => {
       //也可以直接获取当前sheet页的所有内容
      const values = sheet.getSheetValues();
      console.log('--- sheet页的所有内容 -----', i, sheet.name, values);

      sheet.eachRow((row, i) => {
        const rowData: (CellValue | undefined)[] = [];
        row.eachCell((cell: Cell, n) => {
          rowData.push(cell.value);
        });
        let link: any = rowData[0];
        if (link instanceof Object) {
          link = link.hyperlink;
        }
        if (typeof link === 'string' && link.startsWith('http')) {
          const name = rowData[1];
          res.push({
            link,
            name,
          });
        }
      });
    });
    return res;
  }

  @Get('create-html')
  async creteHtmlByExcel() {
    const data = await this.parseExcel();

    let group: any = [];
    for (let i = 0; i < data.length; i += 10) {
      group.push(data.slice(i, i + 10));
    }

    //异步执行group数据，防止卡死，每组间隔2min
    for (let i = 0; i < group.length; i++) {
      await this.excelService.creteHtmlByData(group[i]);
      await new Promise((resolve) => setTimeout(resolve, 60000 * 2));
    }
    return 'ok';
  }
}
